from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
import os

def get_decimal_coordinates(dms, ref):
    """
    将度分秒格式转换为十进制度数
    """
    degrees = dms[0]
    minutes = dms[1]
    seconds = dms[2]
    
    decimal = degrees + (minutes / 60.0) + (seconds / 3600.0)
    
    if ref in ['S', 'W']:
        decimal = -decimal
    
    return decimal

def get_gps_info(image_path):
    """
    从图片中提取GPS信息
    
    Args:
        image_path: 图片文件的绝对路径
    
    Returns:
        tuple: (纬度, 经度) 或 None（如果没有GPS信息）
    """
    try:
        # 检查文件是否存在
        if not os.path.exists(image_path):
            print(f"错误：文件不存在 - {image_path}")
            return None
            
        # 打开图片
        image = Image.open(image_path)
        
        # 获取EXIF数据
        exif = image._getexif()
        if not exif:
            print("未找到EXIF信息")
            return None
            
        # 查找GPS信息
        gps_info = {}
        for tag_id, value in exif.items():
            tag = TAGS.get(tag_id, tag_id)
            if tag == 'GPSInfo':
                for gps_tag in value:
                    sub_tag = GPSTAGS.get(gps_tag, gps_tag)
                    gps_info[sub_tag] = value[gps_tag]
        
        if not gps_info:
            print("未找到GPS信息")
            return None
            
        # 提取经纬度信息
        lat_dms = gps_info.get('GPSLatitude')
        lat_ref = gps_info.get('GPSLatitudeRef')
        lon_dms = gps_info.get('GPSLongitude')
        lon_ref = gps_info.get('GPSLongitudeRef')
        
        if lat_dms and lat_ref and lon_dms and lon_ref:
            latitude = get_decimal_coordinates(lat_dms, lat_ref)
            longitude = get_decimal_coordinates(lon_dms, lon_ref)
            
            print(f"\n图片GPS信息:")
            print(f"纬度: {latitude:.6f}")
            print(f"经度: {longitude:.6f}")
            
            return latitude, longitude
        else:
            print("GPS信息不完整")
            return None
            
    except Exception as e:
        print(f"处理图片时发生错误: {str(e)}")
        return None

if __name__ == '__main__':
    # 测试用例
    image_path = r"D:\xunJi\python\my\tools\images\DJI_20250416180656_0041_V.png"
    coordinates = get_gps_info(image_path)